import { ProjectItem } from "./projectProcessor";

export class ProcessRecorder {
    count: number = 0;
    total: number = 0;
    logger: { log: (message: string) => void };

    skipItems: ProjectItem[] = [];
    errorItems: ProjectItem[] = [];

    constructor() {
        this.logger = console;
    }

    logAddItem(item: ProjectItem) {
        if (item.error) {
            if (item.error.skip) {
                this.printItem(item, "[Skipped]");
                this.skipItems.push(item);
            } else {
                this.printError(item, "[Error]");
                this.errorItems.push(item);
            }
            return;
        } else {
            this.printItem(item, "[Added]");
        }
        this.count++;
        this.total++;
    }

    logState(message: string) {
        this.printBlankLine();
        this.printState(message);
        if (this.skipItems.length !== 0) {
            this.printBlankLine();
            this.logger.log(`[Skipped]:`);
            this.skipItems.map((item) => {
                this.printItem(item, "[Skipped]");
            });
        }
        if (this.errorItems.length !== 0) {
            this.printBlankLine();
            this.logger.log(`[Error]:`);
            this.errorItems.map((item) => {
                this.printError(item, "[Error]");
            });
        }
        this.printBlankLine();
    }

    logProcessItem(item: ProjectItem) {
        if (item.error) {
            if (!item.error.skip) this.printError(item);
            return;
        }
        this.printItem(item, `[Processed] ${this.total - this.count + 1}/${this.total}`);
        this.count--;
    }

    private printItem(item: ProjectItem, message?: string) {
        this.logger.log(`${message ?? "[item]"}: ${item.absolutePath}`);
    }

    private printError(item: ProjectItem, message?: string) {
        this.logger.log(`${message ?? "[Error]"}: ${item.error?.message ?? "unknown"}`);
    }

    private printState(message: string) {
        this.logger.log(message);
        this.logger.log(
            `total: ${this.total}, untreated: ${this.count}, skipped: ${this.skipItems.length}, error: ${this.errorItems.length}`
        );
    }

    private printBlankLine() {
        this.logger.log("");
    }
}
